const http = require('http');
const fs = require('fs');
const path = require('path');
//node服务器用于静态资源访问
exports.upload = function () {
  http.createServer(function (req, res) {
    /*方法一*/
    const fileUrl = __dirname + req.url;
    const fileName = path.resolve(__dirname, "." + req.url);
    const extName = path.extname(fileName).substr(1);
    var mineTypeMap = {
      html: 'text/html;charset=utf-8',
      htm: 'text/html;charset=utf-8',
      xml: "text/xml;charset=utf-8",
      png: "image/png",
      jpg: "image/jpeg",
      jpeg: "image/jpeg",
      gif: "image/gif",
      css: "text/css;charset=utf-8",
      txt: "text/plain;charset=utf-8",
      mp3: "audio/mpeg",
      mp4: "video/mp4",
      ico: "image/x-icon",
      tif: "image/tiff",
      svg: "image/svg+xml",
      zip: "application/zip",
      ttf: "font/ttf",
      woff: "font/woff",
      woff2: "font/woff2",
    }
    fs.readFile(fileUrl, function (err, data) {
      if (err) {
        res.writeHeader(404, {
          'content-type': 'text/html;charset="utf-8"'
        });
        res.write('<div>图片路径错误或图片已被删除</div>');
        res.end();
      } else {
        if (mineTypeMap[extName]) {
          res.setHeader('Content-Type', mineTypeMap[extName]);
        } else {
          res.writeHeader(200, {
            'content-type': 'text/html;charset="utf-8"'
          });
        }
        res.write(data);
        res.end();
      }
    })
  }).listen(9527, () => console.log('图片服务启动成功::::::地址：http://localhost:9527'));
}